package org.dromara.run.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import jodd.util.StringUtil;
import org.dromara.basic.domain.bo.MemberBo;
import org.dromara.basic.domain.vo.MemberVo;
import org.dromara.basic.service.IMemberService;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.run.domain.bo.ApplicationBo;
import org.dromara.run.domain.bo.ScheduleBo;
import org.dromara.run.domain.vo.ScheduleVo;
import org.dromara.run.service.IScheduleService;
import org.springframework.stereotype.Service;
import org.dromara.run.domain.bo.RunListBo;
import org.dromara.run.domain.vo.RunListVo;
import org.dromara.run.domain.RunList;
import org.dromara.run.mapper.RunListMapper;
import org.dromara.run.service.IRunListService;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 阳光跑名单Service业务层处理
 *
 * @author chl
 * @date 2024-08-30
 */
@RequiredArgsConstructor
@Service
public class RunListServiceImpl implements IRunListService {

    private final RunListMapper baseMapper;
    private final IMemberService memberService;
    private final IScheduleService scheduleService;

    /**
     * 查询阳光跑名单
     */
    @Override
    public RunListVo queryById(Long listId){
        RunListVo runListVo = baseMapper.selectVoById(listId);
        if (runListVo != null) {
            MemberVo memberVo = memberService.queryByIdNumber(runListVo.getMemberId(), runListVo.getTenantId());
            runListVo.setMemberInfo(memberVo);
        }
        return runListVo ;
    }

    /**
     * 查询阳光跑名单列表
     */
    @Override
    public TableDataInfo<RunListVo> queryPageList(RunListBo bo, PageQuery pageQuery) {
        QueryWrapper<RunList> lqw = buildQueryWrapper(bo);
        Page<RunListVo> result = baseMapper.selectRunList(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询阳光跑名单列表
     */
    @Override
    public List<RunListVo> queryList(RunListBo bo) {
        QueryWrapper<RunList> lqw = buildQueryWrapper(bo);
        return baseMapper.selectRunList(lqw);
    }

    private QueryWrapper<RunList> buildQueryWrapper(RunListBo bo) {
        Map<String, Object> params = bo.getParams();
        QueryWrapper<RunList> lqw = new QueryWrapper<>();
        lqw.eq(bo.getListId()!=null, "prl.list_id", bo.getListId());
        lqw.eq(StringUtils.isNotBlank(bo.getScheduleId()), "prl.schedule_id", bo.getScheduleId());
        lqw.eq(StringUtils.isNotBlank(bo.getMemberId()), "prl.member_id", bo.getMemberId());
        lqw.eq(StringUtils.isNotBlank(bo.getIsFree()), "prl.is_free", bo.getIsFree());
        lqw.like(StringUtils.isNotBlank(bo.getStudentName()), "pmi.name", bo.getStudentName());
        lqw.eq(StringUtils.isNotBlank(bo.getYears()), "pbtc.years", bo.getYears());
        lqw.eq(StringUtils.isNotBlank(bo.getGender()), "pmi.gender", bo.getGender());
        lqw.eq(StringUtils.isNotBlank(bo.getClassId()), "pmi.class_id", bo.getClassId());
        lqw.eq(StringUtils.isNotBlank(bo.getProfessionalId()), "sd1.dept_id", bo.getProfessionalId());
        lqw.eq(StringUtils.isNotBlank(bo.getCollegeId()), "sd2.dept_id", bo.getCollegeId());
        return lqw;
    }

    /**
     * 新增阳光跑名单
     */
    @Override
    public Boolean insertByBo(RunListBo bo) {
        RunList add = MapstructUtils.convert(bo, RunList.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setListId(add.getListId());
        }
        return flag;
    }

    /**
     * 修改阳光跑名单
     */
    @Override
    public Boolean updateByBo(RunListBo bo) {
        RunList update = MapstructUtils.convert(bo, RunList.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(RunList entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除阳光跑名单
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchCreateRunList(ScheduleBo bo) {
        RunListBo runListBo =new RunListBo();
        runListBo.setScheduleId(bo.getScheduleId().toString());
        List<RunListVo> runListVos = this.queryList(runListBo);
        if(runListVos.size()<0){
            throw new ServiceException("当前计划已经生成");
        }
        ScheduleVo scheduleVo = scheduleService.queryById(bo.getScheduleId());
        if(ObjectUtils.isEmpty(scheduleVo)){
            throw new ServiceException("当前id无法生成名单");
        }
        List<RunList> runLists=new ArrayList<>();
        MemberBo memberBo=new MemberBo();
        memberBo.setTenantId(scheduleVo.getTenantId());
        String grade=scheduleVo.getYears();
        String college = scheduleVo.getCollegeId();
        String yearGroups = scheduleVo.getClassId();
        if (!StringUtil.isEmpty(grade)) {
            List<String> gradeListIds = new ArrayList<>(Arrays.asList(grade.split(",")));
            memberBo.setYearsList(gradeListIds);
        }
        if(!StringUtil.isEmpty(college)){
            List<Long> collegeIds = Arrays.stream(college.split(",")).map(Long::parseLong).collect(Collectors.toList());
            memberBo.setCollegeList(collegeIds);
        }
        if(!StringUtil.isEmpty(yearGroups)){
            List<Long> collegeIds = Arrays.stream(yearGroups.split(",")).map(Long::parseLong).collect(Collectors.toList());

            memberBo.setClassIdList(collegeIds);
        }
        List<MemberVo> memberVos = memberService.queryList(memberBo);
        for (MemberVo memberVo: memberVos) {
            RunList runList=new RunList();
            runList.setMemberId(memberVo.getIdNumber());
            runList.setTenantId(scheduleVo.getTenantId());
            runList.setScheduleId(scheduleVo.getScheduleId().toString());
            runLists.add(runList);
        }
        boolean insertBatch = baseMapper.insertBatch(runLists);
        if(!insertBatch){
            throw new ServiceException("生成名单失败");
        }
        bo.setStatus("1");
        Boolean aBoolean = scheduleService.updateByBo(bo);
        return aBoolean;
    }

    /**
     * 修改阳光跑名单
     */
    @Override
    public Boolean updateByMemberId(ApplicationBo bo) {
        UpdateWrapper updateWrapper=new UpdateWrapper();
        updateWrapper.eq("schedule_id",bo.getScheduleId());
        updateWrapper.eq("id_number",bo.getMemberId());
        updateWrapper.set("is_free","1");
        return baseMapper.update(updateWrapper) > 0;
    }

    @Override
    public Boolean deleteWithMemberId(RunListBo runListBo) {
        QueryWrapper<RunList> queryWrapper=buildQueryWrapper(runListBo);
        return baseMapper.delete(queryWrapper)>0;
    }
}
